package itsm.isperp.module.service.individuation;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.individuation.IddIndividuation;
import itsm.isperp.module.entity.individuation.IddIndividuationProperty;
import itsm.isperp.module.repository.individuation.IddIndividuationMapper;
import itsm.isperp.module.service.app.AppDictService;

import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * 服务
 * 
 * @author lizx
 * @date 2016-10-10 17:41
 */
@Service
public class IddIndividuationService extends BaseService<IddIndividuation> {

	@Autowired
	protected IddIndividuationMapper iddIndividuationMapper;

	@Autowired
	protected JdbcTemplate jdbcTemplate;

	@Autowired
	protected AppDictService appDictService;

	@Override
	public IddIndividuationMapper getRepository() {
		return this.iddIndividuationMapper;
	}

	@Override
	public <S extends IddIndividuation> int saveOrUpdateAndSpecific(S entity, HttpServletRequest req, String... otherFields) {

		Enumeration<String> params = req.getParameterNames();
		Set<String> includeColumns = new HashSet<String>();
		String kid = entity.getId();
		String categoryId = entity.getCategoryId();
		// IddIndividuation model=this.findOne(entity.getId());

		for (; params.hasMoreElements();) {
			String v = params.nextElement();
			if (v.charAt(0) == '_') {
				v = v.substring(1);
			}
			includeColumns.add(v);
		}

		if (otherFields != null) {
			for (String s : otherFields) {
				if (!includeColumns.contains(s))
					includeColumns.add(s);
			}
		}

		// 保存扩展属性 edit at 20160906
		Map<String, String[]> pa = req.getParameterMap();
		if (pa.containsKey("tid_individuationProperty")) {
			IddIndividuationPropertyService iddIndividuationPropertyService = ContextHolder.getSpringBean("iddIndividuationPropertyService");
			Set<String> set = pa.keySet();
			// 插入到扩展表
			String sqlInsert = "";
			String sqlUpdate = "";
			String sqlInsertColumns = "";
			String sqlInsertValues = "";
			boolean ifUpdate = false;
			boolean ifInsert = false;
			String sql = "select * from idd_individuation_form where id='" + categoryId + "' and (db_name is not null and db_name<>'')";
			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
			if (list.size() > 0) {
				String dbName = "idd_db_"+list.get(0).get("db_name").toString();
				String sql0 = "select count(1) from " + dbName + " where relation_id='" + kid + "'";
				Integer ifcount = jdbcTemplate.queryForObject(sql0, Integer.class);
				if (ifcount > 0) {
					sqlUpdate = "update " + dbName + " set ";
				} else {
					sqlInsert = "insert into " + dbName + "";
				}
			}

			for (String k : set) {
				if (k.indexOf("c_") > -1) {
					IddIndividuationProperty ip = new IddIndividuationProperty();
					String kv = "";
					String[] proValue = pa.get(k);
					for (String s1 : proValue) {
						kv += s1 + ",";
					}
					String tk = k.replace("c_", "");
					kv = kv.substring(0, kv.length() - 1);
					String tId = kid + tk;
					ip.setId(tId);
					ip.setRelationId(kid);
					ip.setCategoryPropertyId(tk);
					ip.setValue(kv);
					if (StringUtils.isNotEmpty(kv)) {
						iddIndividuationPropertyService.saveOrUpdate(ip);
						if (StringUtils.isNotBlank(sqlInsert)) {
							sqlInsertColumns += tk + ",";
							sqlInsertValues += "'" + kv + "',";
							ifInsert = true;
						} else if (StringUtils.isNotBlank(sqlUpdate)) {
							sqlUpdate += tk + "='" + kv + "',";
							ifUpdate = true;
						}
					}

				}
			}
			if (ifUpdate) {
				sqlUpdate = sqlUpdate.substring(0, sqlUpdate.length() - 1);
				sqlUpdate += " where relation_id='" + kid + "'";
				jdbcTemplate.execute(sqlUpdate);
			} else if (ifInsert) {
				sqlInsertColumns = sqlInsertColumns.substring(0, sqlInsertColumns.length() - 1);
				sqlInsertValues = sqlInsertValues.substring(0, sqlInsertValues.length() - 1);
				sqlInsert += "(relation_id," + sqlInsertColumns + ") values('" + kid + "'," + sqlInsertValues + ")";
				jdbcTemplate.execute(sqlInsert);
			}
		}

		if (StringUtils.isEmpty(kid)) {
			entity.setId(HibernateUUIDGenerator.generate());
			// 新建事件时默认登记时间以及当前登记者以及初始状态
			entity.setCreateDate(new Timestamp(new java.util.Date().getTime()));
			entity.setCreator(ContextHolder.getLoginUsername());
			entity.setCreatorName(ContextHolder.getLoginUser().getFullname());
			entity.setStatus("新建");

			return this.getRepository().save(entity);
		} else {
			if (this.getRepository().existsByClass(entity.getId(), entity.getClass()) == null) {
				// 新建事件时默认登记时间以及当前登记者以及初始状态
				entity.setCreateDate(new Timestamp(new java.util.Date().getTime()));
				entity.setCreator(ContextHolder.getLoginUsername());
				entity.setCreatorName(ContextHolder.getLoginUser().getFullname());
				entity.setStatus("新建");
				return this.getRepository().save(entity);
			} else {
				this.getRepository().dynamicSpecificUpdate(entity, includeColumns);
			}
			return 1;
		}
	}

	public PageResponse<Map<String, Object>> findWithPropertyMapByRequest(String categoryId, JqGridRequest request) {
		//String sql = "SELECT db_name FROM idd_category_property_setting where id='" + categoryId + "'";
		String dbName = "idd_db_"+categoryId;
		return getRepository().findWithPropertyMapByRequest(dbName, request).toPage();
	}

	public String getProcessKeyByBussinessProcessId(String processId) {
		String sql = "SELECT PROC_DEF_ID_ FROM ACT_RU_TASK where PROC_INST_ID_='" + processId + "'";
		String procDefId = jdbcTemplate.queryForObject(sql, String.class);
		if(StringUtils.isNotBlank(procDefId))
		{
			String[] r=procDefId.split(":");
			return r[0];
		}else
		{
			return "";
		}
	}
	
	public String getCategoryIdByProcessKey(String processKey) {
		String sql = "SELECT relate_form_id FROM bpm_process_setting where act_re_procdef_key='" + processKey + "'";
		String procDefId = jdbcTemplate.queryForObject(sql, String.class);
		if(StringUtils.isNotBlank(procDefId))
		{
			return procDefId;
		}else
		{
			return "";
		}
	}
	
	public String getProcessNameByProcessKey(String processKey) {
		String sql = "SELECT RESOURCE_NAME_ FROM act_re_procdef where key_='" + processKey + "' ORDER BY VERSION_ DESC limit 1";
		String resourceName = jdbcTemplate.queryForObject(sql, String.class);
		if(StringUtils.isNotBlank(resourceName))
		{
			String[] r=resourceName.split("\\.");
			return r[0];
		}else
		{
			return "";
		}
	}
	
  public List<Map<String, Object>> listIddIndividuationProcess() {
    String sql = "SELECT  REPLACE(NAME_, '.bpmn20.xml', '') process_name,c.`db_name` form_db_name FROM act_re_model a"
        + " LEFT JOIN bpm_process_setting b ON a.key_=b.`act_re_procdef_key`"
        + " LEFT JOIN `idd_individuation_form` c ON c.id=b.`relate_form_id`"
        + " WHERE EXISTS (SELECT 1 FROM bpm_process_setting  WHERE act_re_procdef_key = a.`KEY_` AND process_type='individuation' AND relate_form_id IS NOT NULL) GROUP BY KEY_  ORDER BY last_update_time_ ";
    List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
    if (list.size() > 0) {
      return list;
    } else {
      return null;
    }
  }
	
}
